<template>
	<view class="full tab-bar-page booking_page">
		<scroll-view scroll-y class="scrollbar-none h-full">
			<van-form @submit="onSubmit" style="padding-bottom: 100rpx" ref="formRef">
				<van-cell-group inset class="booking_form">
					<van-cell title="基本资料" class="bold"> </van-cell>
					<van-field
						label-width="auto"
						name="reversionName"
						label="预约人姓名"
						v-model="form.reversionName"
						placeholder="请输入请输入真实姓名"
						input-align="right"
						disabled
					/>
					<van-field
						label-width="auto"
						name="reversionPhone"
						label="预约人联系方式"
						v-model="form.reversionPhone"
						placeholder="请输入预约人联系方式"
						input-align="right"
						type="digit"
						disabled
					/>
					<van-field
						readonly
						label="预约人部门"
						name="reversionDeptId"
						input-align="right"
						disabled
					>
						<template #input>
							<span class="disabled-text">{{
								getLabel(departmentList, form.reversionDeptId)
							}}</span>
						</template>
					</van-field>
					<!-- <van-popup
						v-model:show="showDepartmentPicker"
						round
						position="bottom"
					>
						<van-picker
							:columns="departmentList"
							@cancel="showDepartmentPicker = false"
							@confirm="departmentChange"
							:columns-field-names="{ text: 'name', value: 'id' }"
						/>
					</van-popup> -->
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-cell title="预约信息" class="bold"></van-cell>
					<van-field
						v-model="form.visitThemeLabel"
						is-link
						readonly
						label="参观主题"
						placeholder="选择参观主题"
						@click="showVisitThemePicker = true"
						name="visitTheme"
						input-align="right"
						required
						:rules="[{ required: true, message: '请选择参观主题' }]"
						error-message-align="right"
					/>
					<van-popup
						v-model:show="showVisitThemePicker"
						round
						position="bottom"
					>
						<van-picker
							:columns="visitThemeList"
							@cancel="showVisitThemePicker = false"
							@confirm="visitThemeChange"
							:columns-field-names="columnsFieldNames"
						/>
					</van-popup>
					<van-field
						label-width="auto"
						label-align="top"
						name="visitTime"
						label="参观日期"
						input-align="right"
						required
						v-model="form.visitTime"
						:rules="[{ required: true, message: '请选择参观日期' }]"
						error-message-align="right"
					>
						<template #input>
							<DatesAreAvailable
								:dateList="dateList"
								@choose="chooseDate"
								type="in"
								v-model:currentTime="currentTime"
							/>
						</template>
					</van-field>
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-field
						label-width="auto"
						v-model="form.visitNum"
						name="visitNum"
						label="参观人数"
						placeholder="请输入参观人数"
						input-align="right"
						required
						:rules="[{ required: true, message: '请选择参观人数' }]"
						error-message-align="right"
					/>
					<van-field
						v-model="form.groupType"
						is-link
						readonly
						label="群体类型"
						placeholder="选择群体类型"
						@click="showGroupTypePicker = true"
						name="groupType"
						input-align="right"
						required
						:rules="[{ required: true, message: '选择群体类型' }]"
						error-message-align="right"
					/>
					<van-popup v-model:show="showGroupTypePicker" round position="bottom">
						<van-picker
							:columns="groupTypeList"
							@cancel="showGroupTypePicker = false"
							@confirm="groupTypeChange"
							:columns-field-names="columnsFieldNames"
						/>
					</van-popup>

					<van-field
						label-width="auto"
						v-model="form.groupName"
						name="groupName"
						label="群体名称"
						placeholder="请输入群体名称"
						input-align="right"
					/>
					<van-field
						label-width="auto"
						v-model="form.concatName"
						name="concatName"
						label="联系人姓名"
						placeholder="请输入联系人姓名"
						input-align="right"
					/>
					<van-field
						label-width="auto"
						v-model="form.concatPhone"
						name="concatPhone"
						label="联系人电话"
						placeholder="请输入联系人电话"
						input-align="right"
						type="digit"
						:rules="[{ validator: validateMobile, message: '手机号格式错误' }]"
						error-message-align="right"
					/>
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-cell title="客户信息" class="bold"></van-cell>
					<van-field
						label-width="auto"
						v-model="form.companyName"
						name="companyName"
						label="单位名称"
						placeholder="请输入单位名称"
						input-align="right"
						required
						:rules="[{ required: true, message: '请输入单位名称' }]"
						error-message-align="right"
					/>
					<van-field
						label-width="auto"
						v-model="form.corporationCode"
						name="corporationCode"
						label="集团编码"
						placeholder="请输入集团编码"
						input-align="right"
						:rules="[{ required: true, message: '请输入集团编码' }]"
						error-message-align="right"
						required
					/>
					<van-field
						label-width="auto"
						v-model="form.customerName"
						name="customerName"
						label="客户名称"
						placeholder="请输入客户名称"
						input-align="right"
						:rules="[{ required: true, message: '请输入客户名称' }]"
						error-message-align="right"
						required
					/>
					<van-field
						label-width="auto"
						v-model="form.customerProvince"
						name="customerProvince"
						label="所属省份"
						placeholder="请选择客户所属省份"
						input-align="right"
						:rules="[{ required: true, message: '请选择客户所属省份' }]"
						error-message-align="right"
						required
						is-link
						readonly
						@click="showProvincePicker = true"
					>
					</van-field>
					<van-popup v-model:show="showProvincePicker" round position="bottom">
						<van-picker
							:columns="provinceList"
							@cancel="showProvincePicker = false"
							@confirm="provinceChange"
							:columns-field-names="{ text: 'name', value: 'code' }"
						/>
					</van-popup>
					<van-field
						label-width="auto"
						v-model="form.customerCity"
						name="customerCity"
						label="所属城市"
						placeholder="请选择客户所属城市"
						input-align="right"
						error-message-align="right"
						:rules="[{ required: true, message: '请选择客户所属城市' }]"
						required
						is-link
						readonly
						@click="showCityPicker = true"
					>
					</van-field>
					<van-popup v-model:show="showCityPicker" round position="bottom">
						<van-picker
							:columns="cityList"
							@cancel="showCityPicker = false"
							@confirm="cityChange"
							:columns-field-names="{ text: 'name', value: 'code' }"
						/>
					</van-popup>
					<van-field
						v-model="form.customerPosition"
						is-link
						readonly
						label="客户职位"
						placeholder="选择客户职位"
						@click="showCustomerPositionPicker = true"
						name="customerPosition"
						input-align="right"
						error-message-align="right"
						:rules="[{ required: true, message: '请输入客户职位' }]"
						required
					/>
					<van-popup
						v-model:show="showCustomerPositionPicker"
						round
						position="bottom"
					>
						<van-picker
							:columns="customerPositionsList"
							@cancel="showCustomerPositionPicker = false"
							@confirm="customerPositionsChange"
							:columns-field-names="columnsFieldNames"
						/>
					</van-popup>
					<van-field
						v-model="form.customerIndustry"
						is-link
						readonly
						label="所属行业"
						placeholder="选择所属行业"
						@click="showIndustryPicker = true"
						name="industry"
						input-align="right"
						error-message-align="right"
						:rules="[{ required: true, message: '请选择所属行业' }]"
						required
					/>
					<van-popup v-model:show="showIndustryPicker" round position="bottom">
						<van-picker
							:columns="industryList"
							@cancel="showIndustryPicker = false"
							@confirm="industryChange"
							:columns-field-names="columnsFieldNames"
						/>
					</van-popup>
					<van-field
						v-model="form.intentionProduct"
						is-link
						readonly
						label="意向产品"
						placeholder="选择意向产品"
						@click="showIntentionProductPicker = true"
						name="intentionProduct"
						input-align="right"
					/>
					<van-popup
						v-model:show="showIntentionProductPicker"
						round
						position="bottom"
					>
						<van-picker
							:columns="intentionProductList"
							@cancel="showIntentionProductPicker = false"
							@confirm="intentProductChange"
							:columns-field-names="columnsFieldNames"
						/>
					</van-popup>
					<van-field
						label-width="auto"
						name="intensitonFile"
						label="意向解决方案"
						input-align="right"
					>
						<template #input>
							<Upload
								v-model:fileList="form.intensitonFile"
								:showFileList="false"
								@update="getFile"
							>
								<template #uploadAction>
									<el-link type="primary" :underline="false"> 请上传 </el-link>
								</template>
							</Upload>
						</template>
					</van-field>
					<van-cell v-if="form.intensitonFile != ''">
						<view
							v-for="(i, index) in form.intensitonFile.split(',')"
							class="file-list-item"
						>
							<view class="item-left" @click="preview(i)">
								<image
									:src="i"
									class="image"
									v-if="i && getsTheFileType(i)"
								></image>
								<view class="item-content">
									<van-text-ellipsis
										:content="i.slice(i.lastIndexOf('/') + 1)"
									/>
								</view>
							</view>
							<view class="item-button">
								<el-icon @click="deleteFile(index)"><Close /></el-icon>
							</view>
						</view>
					</van-cell>
					<van-field
						label-width="auto"
						v-model="form.customerPhone"
						name="customerPhone"
						label="联系电话"
						placeholder="请输入客户联系电话"
						input-align="right"
						type="digit"
						:rules="[
							{
								required: true,
								message: '请输入客户联系电话',
							},
							{ validator: validateMobile, message: '手机号格式错误' },
						]"
						error-message-align="right"
						required
					/>
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-cell title="是否需要公司领导陪同？" class="bold"></van-cell>
					<van-radio-group v-model="form.needAccompany">
						<van-cell-group inset>
							<van-cell
								:title="i.label"
								clickable
								@click="form.needAccompany = i.value"
								v-for="i in whetherList"
							>
								<template #right-icon>
									<van-radio :name="i.value" />
								</template>
							</van-cell>
						</van-cell-group>
					</van-radio-group>
					<van-field
						label-width="auto"
						name="accompanyLeader"
						label="请选择陪同领导"
						input-align="right"
						:rules="[
							{
								required: form.needAccompany === 'Y',
								message: '请选择陪同领导',
							},
						]"
						error-message-align="right"
						:required="form.needAccompany === 'Y'"
						v-if="form.needAccompany === 'Y'"
					>
						<template #input>
							<van-radio-group
								v-model="form.accompanyLeader"
								direction="horizontal"
							>
								<van-radio :name="i.id" v-for="i in leaderList">{{
									i.name
								}}</van-radio>
							</van-radio-group>
						</template>
					</van-field>
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-cell title="是否需要派车？" class="bold"></van-cell>
					<van-radio-group v-model="form.needCar">
						<van-cell-group inset>
							<van-cell
								:title="i.label"
								clickable
								@click="form.needCar = i.value"
								v-for="i in whetherList"
							>
								<template #right-icon>
									<van-radio :name="i.value" />
								</template>
							</van-cell>
						</van-cell-group>
					</van-radio-group>
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-cell title="是否需要订酒店？" class="bold"></van-cell>
					<van-radio-group v-model="form.needHotel">
						<van-cell-group inset>
							<van-cell
								:title="i.label"
								clickable
								@click="form.needHotel = i.value"
								v-for="i in whetherList"
							>
								<template #right-icon>
									<van-radio :name="i.value" />
								</template>
							</van-cell>
						</van-cell-group>
					</van-radio-group>
				</van-cell-group>
				<van-cell-group inset class="booking_form">
					<van-cell title="是否预约餐饮？" class="bold"></van-cell>
					<van-radio-group v-model="form.needEat">
						<van-cell-group inset>
							<van-cell
								:title="i.label"
								clickable
								@click="form.needEat = i.value"
								v-for="i in whetherList"
							>
								<template #right-icon>
									<van-radio :name="i.value" />
								</template>
							</van-cell>
						</van-cell-group>
					</van-radio-group>
				</van-cell-group>
				<view
					class="booking_button flex justify-around w-full padding-box fix-botton"
					v-if="pageType === 'approval'"
				>
					<van-button
						type="danger"
						size="small"
						style="width: 40%"
						v-if="buttonList && buttonList.indexOf('REFUSE') > -1"
						@click="handleRefuse"
					>
						驳回
					</van-button>
					<van-button
						type="success"
						size="small"
						style="width: 40%"
						v-if="buttonList && buttonList.indexOf('PASS') > -1"
						@click="handlePass"
						:loading="passLoading"
					>
						通过
					</van-button>
				</view>
				<view class="booking_button padding-box w-full" v-else>
					<van-button
						type="primary"
						size="small"
						class="w-full"
						native-type="submit"
						:loading="submitLoading"
						>提交</van-button
					>
				</view>
			</van-form>
		</scroll-view>
		<van-popup
			v-model:show="refuseShow"
			:style="{ padding: '20rpx', borderRadius: '20rpx' }"
		>
			<van-form @submit="confirmRefuse">
				<van-cell-group inset>
					<van-field
						v-model="refuseFormData.reason"
						rows="3"
						autosize
						:label="refuseType === 'jjy' ? '拒绝理由' : '驳回理由'"
						type="textarea"
						placeholder="请输入理由"
						required
						:rules="[{ required: true, message: '请输入理由' }]"
						error-message-align="right"
						clearable
					/>
				</van-cell-group>
				<view style="text-align: right">
					<van-button type="primary" native-type="submit">
						{{ refuseType === "jjy" ? "确认拒绝" : "确认驳回" }}
					</van-button>
				</view>
			</van-form>
		</van-popup>
	</view>
</template>
<script setup>
import DatesAreAvailable from "@/components/datesAreAvailable";
import Upload from "@/components/upload";
import { ArrowRight, Close } from "@element-plus/icons-vue";
import {
	getDeptSelectorrApi,
	addReservationApi,
	getReservationDetailApi,
	reReservationApi,
	editReservationApi,
	getProvApi,
	getCityApi,
	getReservationPasslApi,
	getReservationRefuselApi,
	getAccompanyLeaderApi,
} from "@/api";
import { omit } from "lodash-es";
import { USER_INFO_KEY } from "@/enums/cacheEnum";
import { getLabel, preview, getsTheFileType } from "../../../utils";
import { validateMobile } from "@/utils/rules";
const useDict = useDictStore();
// 判断页面性质 reappointment为重新预约 approval为审批 booking为预约
const props = defineProps({
	pageType: {
		type: String,
		default: "booking",
	},
	// id
	id: {
		type: String || Number,
		default: null,
	},
	// 按钮权限
	buttonList: {
		type: String,
		default: null,
	},
});

// ref
const formRef = ref(null);

// id
const formId = ref(null);

// 判断拒绝弹窗类
const refuseType = ref("");

// 陪同领导
const leaderList = ref([]);

// picker 自定义 columns 结构中的字段
const columnsFieldNames = ref({ text: "label", value: "value" });

// 字典 是否
const whetherList = ref([]);

const userInfo = ref(cache.get(USER_INFO_KEY));

// 可选时间段
const dateList = ref([]);

// 日期选择默认选择
const currentTime = ref(null);

// 表单
const form = ref({
	intensitonFile: "",
	needAccompany: "N",
	accompanyLeader: "",
	needCar: "N",
	needHotel: "N",
	needEat: "N",
	reversionName: userInfo.value.name,
	reversionPhone: userInfo.value.phone,
	reversionDeptId: userInfo.value.deptId,
	orgId: userInfo.value.orgId,
});
const submitLoading = ref(false);
const passLoading = ref(false);
// 群体类型
const groupTypeList = ref([]);
const showGroupTypePicker = ref(false);
const groupTypeChange = ({ selectedOptions }) => {
	form.value.groupType = selectedOptions[0].value;
	form.value.groupTypeLabel = selectedOptions[0].label;
	customerPositionsList.value = selectedOptions[0]?.kid;
	form.value.customerPosition = "";
	showGroupTypePicker.value = false;
};
// 省
const provinceList = ref([]);
const showProvincePicker = ref(false);
const provinceChange = async ({ selectedOptions }) => {
	form.value.customerCityCode = null;
	form.value.customerCity = null;
	form.value.customerProvinceCode = selectedOptions[0].code;
	form.value.customerProvince = selectedOptions[0].name;
	const { data: city } = await getCityApi({
		provCode: form.value.customerProvinceCode,
	});
	cityList.value = city;
	showProvincePicker.value = false;
};
// 城市
const cityList = ref([]);
const showCityPicker = ref(false);
const cityChange = ({ selectedOptions }) => {
	form.value.customerCityCode = selectedOptions[0].code;
	form.value.customerCity = selectedOptions[0].name;
	showCityPicker.value = false;
};
// 客户职位
const customerPositionsList = ref([]);
const showCustomerPositionPicker = ref(false);
const customerPositionsChange = ({ selectedOptions }) => {
	form.value.customerPosition = selectedOptions[0].value;
	showCustomerPositionPicker.value = false;
};
// 所属行业
const industryList = ref([]);
const showIndustryPicker = ref(false);
const industryChange = ({ selectedOptions }) => {
	form.value.customerIndustry = selectedOptions[0].value;
	showIndustryPicker.value = false;
};
// 意向产品
const intentionProductList = ref([]);
const showIntentionProductPicker = ref(false);
const intentProductChange = ({ selectedOptions }) => {
	form.value.intentionProduct = selectedOptions[0].value;
	showIntentionProductPicker.value = false;
};
// 预约人部门
const departmentList = ref([]);
const showDepartmentPicker = ref(false);
const departmentChange = ({ selectedOptions }) => {
	form.value.reversionDeptId = selectedOptions[0].id;
	form.value.reversionDeptName = selectedOptions[0].name;
	showDepartmentPicker.value = false;
};
// 参观主题
const visitThemeList = ref([]);
const showVisitThemePicker = ref(false);
const visitThemeChange = ({ selectedOptions }) => {
	form.value.visitTheme = selectedOptions[0].value;
	form.value.visitThemeLabel = selectedOptions[0].label;
	showVisitThemePicker.value = false;
};

// 日期选择 组件回调
const chooseDate = (res) => {
	form.value.visitDate = res.year + "-" + res.date + " 00:00:00";
	form.value.visitTime = res.timePeriod;
};
// 删除上传文件
const deleteFile = (index) => {
	const list = form.value.intensitonFile.split(",");
	list.splice(index, 1);
	form.value.intensitonFile = list.join(",");

};
// 上传组件获取回显
const getFile = (res) => {
	form.value.intensitonFile = res.map((e) => e.url).join(",");
};

// 通过
const handlePass = async () => {
	if (props.buttonList && props.buttonList.indexOf("EDIT") > -1) {
		try {
			formRef.value.validate().then(async () => {
				passLoading.value = true;
				// 有编辑权限 先编辑保存再审核
				const res = await editReservationApi({
					...omit({ ...form.value }, [
						"groupTypeLabel",
						"reversionDeptName",
						"visitThemeLabel",
					]),
					id: props.id,
				});
				if (res && res.code === 200) {
					await getReservationPasslApi({ id: formId.value });
					feedback.toast("审核已通过");
					setTimeout(() => {
						useTabBar.toMine();
					}, 1000);
				} else if (res.code != 500) {
					feedback.toast(res.msg);
				}
			});
		} catch (error) {
		} finally {
			passLoading.value = false;
		}
	} else {
		await getReservationPasslApi({ id: formId.value });
		feedback.toast("审核已通过");
		setTimeout(() => {
			useTabBar.toMine();
		}, 1000);
	}
};
//拒绝
const refuseShow = ref(false);
const refuseFormData = ref({
	id: null,
	reason: "",
});
// 驳回
const handleRefuse = async () => {
	refuseType.value = "bh";
	refuseFormData.value.id = formId.value;
	refuseShow.value = true;
};
const confirmRefuse = async () => {
	await getReservationRefuselApi(refuseFormData.value);
	feedback.toast((refuseType.value = "jjy" ? "已拒绝" : "审核已驳回"));
	refuseShow.value = false;
	setTimeout(() => {
		useTabBar.toMine();
	}, 1000);
};

// 提交
const onSubmit = async () => {
	try {
		submitLoading.value = true;
		// 预约
		if (!props.pageType || props.pageType === "booking") {
			await addReservationApi({
				...omit({ ...form.value }, [
					"groupTypeLabel",
					"reversionDeptName",
					"visitThemeLabel",
				]),
			});
			feedback.toast("保存成功");
			setTimeout(() => {
				useTabBar.toMine();
			}, 1000);
		} else if (props.pageType === "reappointment") {
			// 重新预约
			await reReservationApi({
				...omit({ ...form.value }, [
					"groupTypeLabel",
					"reversionDeptName",
					"visitThemeLabel",
				]),
				id: props.id,
			});
			feedback.toast("保存成功");
			setTimeout(() => {
				useTabBar.toMine();
			}, 1000);
		}
	} catch (error) {
	} finally {
		submitLoading.value = false;
	}
};

const useTabBar = useTabBarStore();

onMounted(async () => {
	// 获取页面相关数据
	const { data } = await getDeptSelectorrApi("selector");
	departmentList.value = data.map((e) => {
		return {
			label: e.name,
			value: e.id,
		};
	});
	const { data: prov } = await getProvApi();
	provinceList.value = prov;

	visitThemeList.value = useDict.getData("VISIT_THEME");
	groupTypeList.value = useDict.getData("GROUP_TYPE");
	whetherList.value = useDict.getData("YES_NO");
	dateList.value = useDict.getData("INNER_TIME_SLOT");
	industryList.value = useDict.getData("INDUSTRY");
	intentionProductList.value = useDict.getData("INTENTION_PRODUCT");

	const { data: leaderData } = await getAccompanyLeaderApi();
	leaderList.value = leaderData;

	// 页面为重新预约或审批时获取详情
	if (props.id) {
		formId.value = props.id;
		const { data: detail } = await getReservationDetailApi({ id: props.id });
		form.value = detail;
		form.value.intensitonFile
			? (form.value.intensitonFile = form.value.intensitonFile)
			: (form.value.intensitonFile = "");
		currentTime.value =
			form.value.visitYear +
			"-" +
			form.value.visitMonth +
			"-" +
			form.value.visitDay +
			"-" +
			form.value.visitTime;
		form.value.groupTypeLabel = getLabel(
			groupTypeList.value,
			form.value.groupType,
		);
		form.value.visitThemeLabel = getLabel(
			visitThemeList.value,
			form.value.visitTheme,
		);
	}
}),
	onShow(() => {
		if (!props.pageType) {
			useTabBar.setTab();
		}
	});
</script>
<style lang="scss" scoped>
.booking_ {
	&page {
		.booking-form {
			padding-bottom: 100rpx;
		}
		.padding-box {
			padding: var(--van-cell-vertical-padding)
				var(--van-cell-horizontal-padding);
			box-sizing: border-box;
		}
	}
	&form {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		.bold {
			:deep(.van-cell__title) {
				font-weight: bold;
			}
		}
		.file-list-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			margin-bottom: 10px;
			.item-left {
				display: flex;
				align-items: center;
				width: calc(100% - 30rpx);
				.image {
					height: 80rpx;
					width: 80rpx;
					margin-right: 20rpx;
				}
			}
			.item-buttonn {
				width: 30rpx;
				height: 30rpx;
			}
			.item-content {
				font-weight: bold;
				width: calc(100% - 80rpx);
				text-align: left;
			}
		}
	}

	&button {
		background-color: $uni-bg-color-grey !important;
		box-sizing: border-box;
	}
}
.fix-botton {
	position: fixed;
	bottom: 0;
}
</style>
